package com.df.gamesynctest.handler;

import com.df.gamesynctest.entity.*;
import com.df.gamesynctest.msg.*;
import com.df.gamesynctest.net.MsgSend;

import java.util.ArrayList;
import java.util.List;

public class MsgHandler {

    private static MsgHandler instance = new MsgHandler();
    private MsgHandler(){}
    public  static MsgHandler getInstance(){
         return instance;
     }

    public void handleMsg(MsgWrapper msg){
        //TODO 提前收集消息类型和消息处理脚本的映射，根据消息id或消息类型找到处理脚本，然后执行脚本
        // 这里可以根据具体业务进行处理
        try {
            int playerId = msg.playerId;
            Player player = UserManager.getInstance().id2player.get(playerId);
            handleMsgDo(player,msg.msg);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void handleMsgDo(Player player, Object msg) {
        if(msg instanceof C2S_EnterMap){
            handleEnterMap(player,(C2S_EnterMap) msg);
            return;
        }
        if(msg instanceof C2S_EnterMapSuccess){
            handleEnterMapSuccess(player,(C2S_EnterMapSuccess) msg);
            return;
        }
        if(msg instanceof C2S_Move){
            handleMove(player,(C2S_Move) msg);
            return;
        }
    }

    private void handleMove(Player player, C2S_Move msg) {
        //移动逻辑
        //TODO 处理移动逻辑，包括移动位置、处理碰撞等
        player.moveDir.x = msg.x;
        player.moveDir.y = msg.y;

        List<Player> aroundPlayer = player.map.findAroundPlayer(player.pos);
        aroundPlayer.remove(player);
        if(!aroundPlayer.isEmpty()){
            S2C_PlayerMove res = new S2C_PlayerMove();
            res.id = player.id;
            res.x = msg.x;;
            res.y = msg.y;
            res.speed = player.speed;;
            MsgSend.broadMsg(aroundPlayer,res);
        }
    }

    private void handleEnterMapSuccess(Player player, C2S_EnterMapSuccess msg) {
        //同步周围信息给玩家
        //玩家
        //怪物
        List<Monster> aroundMonster = player.map.findAroundMonster(player.pos);
        List<MonsterData> sendData = new ArrayList<>();
        for (Monster monster : aroundMonster) {
            MonsterData d = new MonsterData();
            d.id = monster.id;
            d.posX = (float) monster.pos.x;
            d.posY = (float) monster.pos.y;
            d.moveTargetX = (float) monster.moveTarget.x;
            d.moveTargetY = (float) monster.moveTarget.y;
            d.speed = monster.speed;
            sendData.add(d);
        }
        //npc
        //触发器等等
        S2C_SynAroundObjs res = new S2C_SynAroundObjs();
        res.monsterList.addAll(sendData);
        MsgSend.sendMsg(player,res);

    }

    private void handleEnterMap(Player player, C2S_EnterMap msg) {
        if(player==null){
            return;
        }
        System.out.println(player.id+"进入地图");

        player.pos.x =msg.x;
        player.pos.y =msg.y;
        //TODO 客户端主动进入地图，检测进入逻辑，看能否进入
        //将玩家加入地图
        GameMap.getInstance().playerEnterMap(player);
    }
}
